#!/usr/bin/env python3
"""
MCP Environment Fix Script
自动修复MCP环境问题的脚本

Usage:
    python test/fix_environment.py
"""

import sys
import os
import subprocess
import shutil
from pathlib import Path

def fix_virtual_environment():
    """修复虚拟环境"""
    print("🔧 Fixing virtual environment...")
    
    project_root = Path(__file__).parent.parent
    venv_path = project_root / ".venv"
    
    # Remove existing broken venv
    if venv_path.exists():
        print("Removing existing virtual environment...")
        try:
            shutil.rmtree(venv_path)
            print("✅ Old virtual environment removed")
        except Exception as e:
            print(f"❌ Error removing venv: {e}")
            return False
    
    # Create new venv with Python 3.11
    print("Creating new virtual environment with Python 3.11...")
    try:
        result = subprocess.run(
            ["uv", "venv", "--python", "3.11"],
            cwd=project_root,
            capture_output=True,
            text=True
        )
        
        if result.returncode == 0:
            print("✅ Virtual environment created successfully")
            return True
        else:
            print(f"❌ Failed to create venv: {result.stderr}")
            return False
            
    except Exception as e:
        print(f"❌ Error creating venv: {e}")
        return False

def install_dependencies():
    """安装依赖"""
    print("\n🔧 Installing dependencies...")
    
    project_root = Path(__file__).parent.parent
    
    try:
        result = subprocess.run(
            ["uv", "sync"],
            cwd=project_root,
            capture_output=True,
            text=True
        )
        
        if result.returncode == 0:
            print("✅ Dependencies installed successfully")
            return True
        else:
            print(f"❌ Failed to install dependencies: {result.stderr}")
            return False
            
    except Exception as e:
        print(f"❌ Error installing dependencies: {e}")
        return False

def test_installation():
    """测试安装是否成功"""
    print("\n🧪 Testing installation...")
    
    project_root = Path(__file__).parent.parent
    
    try:
        # Test imports
        result = subprocess.run(
            ["uv", "run", "python", "-c", 
             "import fastmcp, pyside6, psutil, markdown; print('All imports successful')"],
            cwd=project_root,
            capture_output=True,
            text=True
        )
        
        if result.returncode == 0:
            print("✅ All dependencies can be imported")
            
            # Test server startup
            print("Testing server startup...")
            result = subprocess.run(
                ["uv", "run", "server.py"],
                cwd=project_root,
                timeout=5,
                capture_output=True,
                text=True
            )
            
            return True
            
        else:
            print(f"❌ Import test failed: {result.stderr}")
            return False
            
    except subprocess.TimeoutExpired:
        print("✅ Server started successfully (timeout expected)")
        return True
    except Exception as e:
        print(f"❌ Test failed: {e}")
        return False

def create_mcp_config_template():
    """创建MCP配置模板"""
    print("\n📝 Creating MCP configuration template...")
    
    project_root = Path(__file__).parent.parent
    config_template = project_root / "test" / "claude_desktop_config_template.json"
    
    config_content = {
        "mcpServers": {
            "interactive-feedback": {
                "command": "uv",
                "args": [
                    "--directory", 
                    str(project_root).replace("\\", "/"),
                    "run", 
                    "server.py"
                ],
                "timeout": 600,
                "autoApprove": ["interactive_feedback"]
            }
        }
    }
    
    try:
        import json
        with open(config_template, 'w', encoding='utf-8') as f:
            json.dump(config_content, f, indent=2, ensure_ascii=False)
        
        print(f"✅ Configuration template created: {config_template}")
        print("\nTo use this configuration:")
        print("1. Copy the content of this file")
        print("2. Paste it into your Claude Desktop configuration file")
        print("3. Adjust the path if necessary")
        
        return True
        
    except Exception as e:
        print(f"❌ Error creating config template: {e}")
        return False

def create_test_scripts():
    """创建测试脚本的快捷方式"""
    print("\n📝 Creating test script shortcuts...")
    
    project_root = Path(__file__).parent.parent
    
    # Create run_tests.bat for Windows
    if sys.platform == "win32":
        bat_content = f"""@echo off
cd /d "{project_root}"
echo Running MCP Server Tests...
uv run test/test_mcp_server.py
pause
"""
        
        bat_file = project_root / "run_tests.bat"
        try:
            with open(bat_file, 'w', encoding='utf-8') as f:
                f.write(bat_content)
            print(f"✅ Created Windows test script: {bat_file}")
        except Exception as e:
            print(f"❌ Error creating bat file: {e}")
    
    # Create run_tests.sh for Unix-like systems
    sh_content = f"""#!/bin/bash
cd "{project_root}"
echo "Running MCP Server Tests..."
uv run test/test_mcp_server.py
"""
    
    sh_file = project_root / "run_tests.sh"
    try:
        with open(sh_file, 'w', encoding='utf-8') as f:
            f.write(sh_content)
        
        # Make executable on Unix-like systems
        if sys.platform != "win32":
            os.chmod(sh_file, 0o755)
        
        print(f"✅ Created Unix test script: {sh_file}")
        return True
        
    except Exception as e:
        print(f"❌ Error creating sh file: {e}")
        return False

def main():
    """运行所有修复步骤"""
    print("🔧 MCP Environment Fix Tool")
    print("="*50)
    print("This script will fix common MCP environment issues.")
    print()
    
    # Confirm before proceeding
    response = input("Do you want to proceed? (y/N): ").strip().lower()
    if response not in ['y', 'yes']:
        print("Operation cancelled.")
        return
    
    print("\nStarting environment fix...")
    
    steps = [
        ("Fix Virtual Environment", fix_virtual_environment),
        ("Install Dependencies", install_dependencies),
        ("Test Installation", test_installation),
        ("Create MCP Config Template", create_mcp_config_template),
        ("Create Test Scripts", create_test_scripts),
    ]
    
    results = []
    
    for step_name, step_func in steps:
        print(f"\n{'='*50}")
        print(f"Step: {step_name}")
        print('='*50)
        
        try:
            result = step_func()
            results.append((step_name, result))
            
            if not result:
                print(f"❌ Step failed: {step_name}")
                print("Fix process stopped. Please check the error above.")
                break
                
        except Exception as e:
            print(f"❌ Step failed with exception: {e}")
            results.append((step_name, False))
            break
    
    # Summary
    print(f"\n{'='*50}")
    print("FIX SUMMARY")
    print('='*50)
    
    for step_name, result in results:
        status = "✅ SUCCESS" if result else "❌ FAILED"
        print(f"{step_name}: {status}")
    
    if all(result for _, result in results):
        print("\n🎉 Environment fix completed successfully!")
        print("\nNext steps:")
        print("1. Copy the MCP configuration from test/claude_desktop_config_template.json")
        print("2. Add it to your Claude Desktop configuration")
        print("3. Restart Claude Desktop")
        print("4. Test the MCP server with: uv run test/test_mcp_server.py")
    else:
        print("\n⚠️ Some steps failed. Please check the errors above.")

if __name__ == "__main__":
    main()
